<template>
  <div class="learn-detail">
    <!-- 面包屑 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ name: 'LearnList' }">学习路径列表</el-breadcrumb-item>
      <el-breadcrumb-item>
        {{ editMode ? `编辑学习路径详情 -- ${title}` : '新增学习路径详情' }}
      </el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 折叠面板 -->
    <el-collapse v-model="collapse">
      <el-collapse-item title="学习路径元数据编辑" name="1">
        <el-form :model="info" :rules="learnPathRule" ref="learnPathForm">
          
          <el-row :gutter="30">
            <el-col :span="8">
              <el-form-item prop="title" label="名称">
                <el-input v-model="info.title"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item prop="summary" label="介绍">
                <el-input v-model="info.summary"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item prop="payMode" @click="payModeChange" label="模块付费类型">
                <pay-sl v-model="info.payMode"></pay-sl>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="30">
            <el-col :span="4">
              <el-form-item prop="online" label="上下线状态">
                <online-sl v-model.number="info.online"></online-sl>
              </el-form-item>
            </el-col>
            <el-col :span="4">
              <el-form-item prop="platform" label="使用平台">
                <client-sl v-model.number="info.platform"></client-sl>
              </el-form-item>
            </el-col>
            <el-col :span="4" v-if="info.payMode !== '0'">
              <el-form-item prop="price" label="价格(元)">
                <el-input-number style="width:190px" :controls="false" :precision="2" :step="0.01" v-model.number="info.price" placeholder="最多精确到分"></el-input-number>
                <!-- <pay-range-sl v-model="info.price"></pay-range-sl> -->
              </el-form-item>
            </el-col>
            <el-col :span="4">
              <el-form-item prop="showPrice" label="划线价格(元)" >
                <el-input-number style="width:190px" :controls="false" :precision="2" :step="0.01" v-model.number="info.showPrice" placeholder="最多精确到分"></el-input-number>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="3">
              <el-form-item prop="cover" label="背景图">
                <upload-resource is-public @upload="(img) => $set(info, 'cover', img.url)" folder="cover"></upload-resource>
                <el-button @click="$set(info, 'cover', '')" type="text" class="danger-text" v-if="this.info.cover">
                  删除图片
                </el-button>
              </el-form-item>
            </el-col>
            <el-col :span="5">
              <img style="max-height: 150px;" :src="info.cover" v-if="info.cover" />
            </el-col>
            <el-col :span="3">
              <el-form-item prop="bannerImg" label="PC背景图">
                <upload-resource is-public @upload="(img) => $set(info, 'bannerImg', img.url)" folder="cover"></upload-resource>
                <el-button @click="$set(info, 'bannerImg', '')" type="text" class="danger-text" v-if="this.info.bannerImg">
                  删除图片
                </el-button>
              </el-form-item>
            </el-col>
            <el-col :span="5">
              <img style="max-height: 150px;" :src="info.bannerImg" v-if="info.bannerImg" />
            </el-col>
            <el-col :span="3">
              <el-form-item prop="image" label="封面图">
                <upload-resource is-public @upload="(img) => $set(info, 'image', img.url)" folder="cover"></upload-resource>
                <el-button @click="$set(info, 'image', '')" type="text" class="danger-text" v-if="this.info.image">
                  删除图片
                </el-button>
              </el-form-item>
            </el-col>
            <el-col :span="5">
              <img style="max-height: 150px;" :src="info.image" v-if="info.image" />
            </el-col>
          </el-row>
          <el-row>
            <el-button type="success" v-if="editMode" @click="save" :loading="saving" v-permission="['learn:dataAdd']">
              保存学习路径基本配置
            </el-button>
            <el-button type="primary" v-else @click="save" :loading="saving" v-permission="['learn:dataAdd']">新增学习路径</el-button>
          </el-row>
        </el-form>
      </el-collapse-item>
      <el-collapse-item title="学习路径下数据编辑" name="2" v-if="info.id">
        <div class="learn-path">
          <span>学习路径数据列表</span>
          <span class="learn-path-icon">
            <i :class="{'el-icon-s-operation':true,'is-active':!isActive}" @click="()=>isActive=false"></i>
            <i :class="{'el-icon-menu':true,'is-active':isActive}" @click="()=>isActive=true"></i>
          </span>
          <!-- 表格数据 -->
          <el-table :data="elementList" tooltip-effect="dark" v-show="!isActive" row-key="courseId">
            <el-table-column label="序列" type="index" align="center" show-overflow-tooltip></el-table-column>
            <el-table-column label="标题" prop="title" align="center" show-overflow-tooltip></el-table-column>
            <el-table-column label="讲数" prop="lessionCnt" align="center" show-overflow-tooltip></el-table-column>
            <el-table-column label="金额" prop="payPrice" align="center" show-overflow-tooltip>
              <template slot-scope="scope">
                <span>{{  scope.row.payPrice}}元</span>
                <!-- <span>{{ scope.row.showPrice ? scope.row.showPrice : scope.row.payPrice ? scope.row.payPrice : '0' }}元</span> -->
              </template>
            </el-table-column>
            <el-table-column label="付费类型" align="center" show-overflow-tooltip>
              <template slot-scope="scope">
                {{ scope.row.payMode===undefined ? '' : scope.row.payMode ? $selectFormat['paySl'](scope.row.payMode).label : ''}}
              </template>
            </el-table-column>
            <el-table-column label="难度" align="center" show-overflow-tooltip>
              <template slot-scope="scope">
                {{ scope.row.level===undefined ? '' :  $selectFormat['courseLevelSl'](scope.row.level).label }}
              </template>
            </el-table-column>
            <el-table-column label="操作" align="center" width="500px">
                <template slot-scope="scope">
                  <el-button icon="el-icon-rank">点我拖动</el-button>
                  <el-button type="primary" @click="()=>isActive=true">跳转到目标学习路径数据</el-button>
                  <el-button type="danger" icon="el-icon-delete" @click="delOneItem(scope.row)"  v-permission="['learn:dataDelete']">移除学习路径数据</el-button>
                </template>
            </el-table-column>
          </el-table>
          <!-- 块数据 -->
          <draggable v-model="elementList" handle=".drag-btn" v-show="isActive">
            <div class="element learn-path-item" v-for="(element, index) in elementList" :key="index">
              <div class="element-body">
                <div class="element-order">
                  <el-button icon="el-icon-rank" class="drag-btn">拖我移动</el-button>
                  <el-checkbox v-model="element.checked" label="选中" style="margin-left: 10px" @change="elementChange(element.checked, index)"></el-checkbox>
                </div>
                <div class="learn-path-info">
                  <el-row>
                    <el-col :span="3">
                      <span>标题:</span>
                      <p>{{element.title}}</p>
                    </el-col>
                    <el-col :span="7" :offset="1">
                      <span>难度:</span>
                      <p>{{ element.level===undefined ? '' : $selectFormat['courseLevelSl'](element.level).label}}</p>
                    </el-col>
                    <el-col :span="7" :offset="1">
                      <span>讲数:</span>
                      <p>{{element.lessionCnt}}</p>
                    </el-col>
                  </el-row>
                  <el-row>
                    <el-col :span="3">
                      <span>金额:</span>
                      <span>{{  element.payPrice}}元</span>
                      <!-- <p>{{element.showPrice ? element.showPrice : element.payPrice ? element.payPrice : ''}}元</p> -->
                    </el-col>
                    <el-col :span="7" :offset="1">
                      <span>付费类型:</span>
                      <p>{{ element.payMode===undefined ? '' : $selectFormat['paySl'](element.payMode).label}}</p>
                    </el-col>
                    <el-col :span="7" :offset="1">
                      <span>课程封面:</span>
                      <img :src="element.cover" alt="">
                    </el-col>
                  </el-row>
                </div>
                <!-- <el-switch v-model="element.online" active-color="#13ce66" inactive-color="#ff4949" active-text="已上线" :active-value="1" inactive-text="未上线" :inactive-value="0"></el-switch> -->
              </div>
            </div>
          </draggable>
          <edit-bar>
            <el-checkbox label="全选" v-model="checkAll" v-show="isActive" @change="handleCheckAllChange"></el-checkbox>
            <el-button type="danger" icon="el-icon-close" @click="del" v-show="isActive" :disabled="selectedElement.length === 0" v-permission="['learn:dataDelete']">删除数据 </el-button>
            <!-- 图片 -->
            <div class="selected-element-box" v-if="selectedElement.length > 0">
              <span class="item" v-for="(element, index) in selectedElement" :key="index">
                <el-tooltip class="item" effect="dark" :content="element.title" placement="top">
                  <img :src=" `${element.cover}?x-oss-process=image/resize,m_fill,h_30,w_30`"/>
                </el-tooltip>
              </span>
            </div>

            <template slot="right">
              <data-pool btn-text="添加数据" @select="dataPoolSelect"></data-pool>
              <el-button type="primary" icon="el-icon-check" @click="saveElementList" :loading="elementSaving" v-permission="['learn:dataSave']">保存学习路径下的数据</el-button>
              <el-button type="success" icon="el-icon-upload" @click="publich" v-permission="['learn:dataPublich']">发布学习路径下的数据</el-button>
            </template>
          </edit-bar>
        </div>

      </el-collapse-item>
    </el-collapse>
  </div>
</template>
<script>
import EditMixins from 'mixins/Edit';
import { FormRuleConf } from '@/config';
import DataPool from 'comp/DataPool';
import EditBar from 'comp/EditBar';
// import DynamicForm from 'comp/DynamicForm';
import UploadResource from 'comp/UploadResource';
// import ModuleType from 'config/ModuleType';'

import CustomSelectData from 'config/CustomSelectData';

import Sortable from 'sortablejs'
export default {
  mixins: [EditMixins],
  components:{
    UploadResource,EditBar,DataPool,
  },
  computed: {
    selectedElement() {
      return this.elementList.filter((element) => element.checked);
    },
    checkAll: {
      get() {
        return (
          this.selectedElement.length > 0 &&
          this.selectedElement.length == this.elementList.length
        );
      },
      set(val) {},
    },
  },
  watch:{
    isActive(value){
      if(!value){
        this.rowDrop()
      }
    }
  },
  data() {
    return {
      collapse: ['2'],
      title: '',
      // 验证规则
      ...FormRuleConf.LearnPath,
      // ModuleType,
      // 模块下的数据
      elementList:[],
      // 保存
      elementSaving:false,

      // 切换是否active
      isActive:true,
    }
  },
  methods: {
    // 付费类型为免费的时候
    payModeChange(){
      if(this.info.payMode === 0){
        this.info.price = 0
      }
    },
    // 学习路径选择
    elementChange(val, index) {
      this.elementList = this.elementList.map((element, i) => {
        if (index == i) element.checked = val;
        return element;
      });
    },
    // 学习路径全选
    handleCheckAllChange(val){
      this.checkAll = val;
      // 全选
      if (val) {
        this.elementList = this.elementList.map((element) => {
          element.checked = true;
          return element;
        });
      // 全不选
      } else {
        this.elementList = this.elementList.map((element) => {
          element.checked = false;
          return element;
        });
      }
    },
    // 删除学习路径数据
    del(){
      this.selectedElement.forEach(item=>{
        this.elementList.forEach((item1,index)=>{
          if(item.title == item1.title){
            this.elementList.splice(index,1)
          }
        })
      })
      this.saveElementList()
    },
    // 表格模式下，删除单条数据
    delOneItem(val){
      this.elementList.forEach((item1,index)=>{
        if(val.title == item1.title){
          this.elementList.splice(index,1)
        }
      })
      this.saveElementList()
    },
    // 选择数据池数据
    dataPoolSelect(selectedData){
      let data = JSON.parse(JSON.stringify(selectedData))
      data.map((item,index)=>{
        // 需要把id赋给courseId
        item.courseId = item.id
        // 处理显示的价格
        if(item.payPrice){
          let str1 = (item.payPrice/100) + '';
          let intSum1 = str1.substring(0,str1.indexOf(".")).replace( /\B(?=(?:\d{3})+$)/g, ',' );//取到整数部分
          let dot1 = str1.substring(str1.length,str1.indexOf("."))//取到小数部分
          item.payPrice = intSum1 + dot1;
        }
      })
      this.elementList = [...data].concat([...this.elementList]);
    },
    // 保存学习路径下的数据
    saveElementList(){
      if (this.elementSaving) return Promise.reject();
      
      let arr = []
      this.elementList.map((item,index)=>{
        arr.push({
          "courseId": item.courseId ? item.courseId : 0,
			    "pathId": this.id,
			    "videoId": item.videoId ? item.videoId : 0,
          "sortnum": index
        })
      })
      
      this.elementSaving = true;
      return this.$service.LearnpathSaveCourses({
        "courses": arr,
        "pathId": this.id,
      },JSON_HEADER).then((res) => {
        this.$message.success('保存数据源成功!');
        // 刷新数据源列表
        this.getElementList();
      })
      .finally(() => {
        this.elementSaving = false;
      });
    },
    // 发布
    publich(){
      this.$confirm('确认要发布到线上去吗?发布了就真的上线了!!!!').then(() => {
        this.saveElementList().then(() => {
          this.$service
            .LearnpathPublish({
              pathId: this.id,
            })
            .then((res) => {
              this.$message.success('发布完成');
            })
        });
      });
    },
    /**
     * 新增或者保存学习路径信息
     */
    save(){
      if (this.saving) return;

      this.$refs['learnPathForm'].validate((valid) => {
        if (valid) {
          this.saving = true;
          // 处理价格,因为一个选项的上传两个数据
          // if(this.info.price){
          //   this.info.appleProductId = this.info.price.split(',')[1]
          //   this.info.price = this.info.price.split(',')[0]
          // }else{
          //   this.info.appleProductId = ''
          //   this.info.price = 0
          // }

          this.$service
            .LearnpathSave(this.info, JSON_HEADER)
            .then((res) => {
              this.$message.success('学习路径操作成功!');
              this.$tabs.open({ name: 'LearnDetail', params: { id: res } });
            })
            .finally(() => {
              this.saving = false;
            });
        }
      });
    },
    /**
     * 获取学习路径信息
     */
    getInfo() {
      if (!this.id || this.infoGetting) return;

      this.infoGetting = true;
      this.$service.
        LearnpathDetail({ pathId: this.id })
        .then((res) => {
          this.info = { ...res };
          // QUAN
          // 处理数据
          // if(this.info.price){
          //   CustomSelectData.payRangeSl.map((item)=>{
          //     if(item.value.indexOf(this.info.price)!==-1){
          //       this.info.price = item.value
          //     }
          //   })
          // }
          this.title = res.title;
          return this.getElementList();
        })
        .finally(() => {
          this.infoGetting = false;
        });     
    },
    /**
     * 获取学习路径下的数据
     */
    getElementList() {
      if (!this.id) return;
      this.elementList = [];
      this.$service.LearnpathPreview({ pathId: this.id }).then((res) => {
        this.elementList = res;
      });
    },
    // 行拖拽
    rowDrop () {
      // 此时找到的元素是要拖拽元素的父容器
      const tbody = document.querySelector('.el-table__body-wrapper tbody');
      const _this = this;
      Sortable.create(tbody, {
        // 指定父元素下可被拖拽的子元素
        draggable: ".el-table__row",
        onEnd ({ newIndex, oldIndex }) {
          const currRow = _this.elementList.splice(oldIndex, 1)[0];
          _this.elementList.splice(newIndex, 0, currRow);
        }
      });
    },
  },
  created() {
    
  },
  mounted() {
  },
}
</script>
<style lang="less" scoped>
// 选择时候展示图片
.selected-element-box {
  display: flex;
  padding-left: 5px;
  .item {
    margin-right: 5px;
    cursor: pointer;
  }
}
// 学习路径数据展示盒子
.learn-path{
  .learn-path-icon{
    float: right;

    i{
      margin-left: 10px;
      font-size: 16px;

      &:hover{
        color:#409EFF;
      }

    }
    & .is-active{
      color:#409EFF;
    }
  }
  .learn-path-item{
    // 加编号
    .order-increment;
    padding: 10px;
    background-color: #eee;
    border-radius: 5px;
    margin-bottom: 5px;
    position: relative;
    min-height: 50px;
  }
  margin-bottom: 50px;

  /deep/ .el-table{
    th{
      background-color: #e5e5e5 !important;
    }
  }
}
</style>